#!/bin/bash

set -e
# 由gpt（deepseek）翻译
# 该脚本用于为 Android 平台交叉编译 Cuberite。它使用以下环境变量：
#   CMAKE: 应为版本 3.12.4 以上的 cmake 可执行文件的路径
#   NDK: 应为 Android NDK 根目录的路径
#   (可选) TYPE: 可以是 Release 或 Debug，设置构建类型
#   (可选) THREADS: 要使用的线程数，默认为 4
function usage() {
	echo "用法: NDK=<ndk路径> CMAKE=<cmake二进制文件> $0 (clean|<ABI>)";
	exit 1
}

BASEDIR="$(realpath $(dirname $0))"
BUILDDIR="$BASEDIR/../android-build"
SELF="./$(basename $0)"

# Clean 操作不需要 CMAKE 和 NDK，因此在这里处理
if [ "$1" == "clean" ]; then
	rm -rf $BUILDDIR
	exit 0
fi

if [ -z "$CMAKE" -o -z "$NDK" ]; then
	usage;
fi

# CMake 需要绝对路径
CMAKE="$(realpath $CMAKE)"
NDK="$(realpath $NDK)"

if [ -z "$TYPE" ]; then
	TYPE="Release"
fi

if [ -z "$THREADS" ]; then
	THREADS="4"
fi

cd "$BASEDIR"

case "$1" in

	armeabi-v7a)
		APILEVEL=16
	;;

	arm64-v8a)
		APILEVEL=21
	;;

	x86)
		APILEVEL=16
	;;

	x86_64)
		APILEVEL=21
	;;

	all)
		echo "正在打包 server.zip ..."
		rm -rf Server
		mkdir -p Server

		for arch in armeabi-v7a arm64-v8a x86 x86_64; do
			echo "正在处理 ... $arch ..." && \
			cd $BASEDIR && \
			"$SELF" clean && \
			"$SELF" "$arch" && \
			cd $BUILDDIR/Server && \
			zip $BASEDIR/Server/"$arch".zip Cuberite
		done

		echo "正在打包 server.zip ..."
		cd $BUILDDIR/Server
		zip -r $BASEDIR/Server/server.zip -@ -x Cuberite < Install/UnixExecutables.list

		cd $BASEDIR/Server
		for file in server.zip armeabi-v7a.zip arm64-v8a.zip x86.zip x86_64.zip; do
			echo "正在为 ... $file ... 生成 sha1 校验和 ..." && \
			sha1sum "$file" > "$file".sha1
		done

		echo "完成！构建的 zip 文件在 Server/ 目录中等待您"
		exit;
	;;

	*)
		usage;
	;;
esac

mkdir -p "$BUILDDIR"
cd "$BUILDDIR"
"$CMAKE" "$BASEDIR/../android" -DCMAKE_TOOLCHAIN_FILE="$NDK/build/cmake/android.toolchain.cmake" \
    -DANDROID_ABI="$1" \
    -DANDROID_NATIVE_API_LEVEL="$APILEVEL" \
    -DCMAKE_BUILD_TYPE="$TYPE" \
	-DWHOLE_PROGRAM_OPTIMISATION=No

make -j "$THREADS"
